using SqlSugar;
using System.Configuration;

namespace CaipuGuanliXitong.Models;

public class CookBookDbContext
{
    public SqlSugarScope Db;

    public CookBookDbContext()
    {
        Db = new SqlSugarScope(new ConnectionConfig()
        {
            DbType = DbType.Sqlite,
            ConnectionString = "Data Source=CookBook.db",
            InitKeyType = InitKeyType.Attribute,
            IsAutoCloseConnection = true
        });
        
        // 创建数据库和表
        InitDatabase();
    }

    private void InitDatabase()
    {
        // 创建数据库（如果不存在）
        Db.DbMaintenance.CreateDatabase();
        
        // 检查是否需要重新创建表（通过环境变量控制）
        var recreateTables = Environment.GetEnvironmentVariable("RECREATE_DATABASE_TABLES");
        if (!string.IsNullOrEmpty(recreateTables) && recreateTables.ToLower() == "true")
        {
            ReCreateDatabase();
        }
        else
        {
            // 创建表（如果不存在）
            InitTables();
        }
    }

    public void ReCreateDatabase()
    {
        // 删除所有表
        DropAllTables();
        
        // 重新创建表
        InitTables();
    }

    private void DropAllTables()
    {
        // 按正确的依赖顺序删除表
        if (Db.DbMaintenance.IsAnyTable("RecipeIngredient", false)) 
            Db.DbMaintenance.DropTable("RecipeIngredient");
        
        if (Db.DbMaintenance.IsAnyTable("WeeklyMenu", false)) 
            Db.DbMaintenance.DropTable("WeeklyMenu");
        
        if (Db.DbMaintenance.IsAnyTable("DailyPurchaseDetail", false)) 
            Db.DbMaintenance.DropTable("DailyPurchaseDetail");
        
        if (Db.DbMaintenance.IsAnyTable("DailyPurchase", false)) 
            Db.DbMaintenance.DropTable("DailyPurchase");
        
        if (Db.DbMaintenance.IsAnyTable("Ingredient", false)) 
            Db.DbMaintenance.DropTable("Ingredient");
        
        if (Db.DbMaintenance.IsAnyTable("CookBook", false)) 
            Db.DbMaintenance.DropTable("CookBook");
    }

    private void InitTables()
    {
        // 创建表（按正确的依赖顺序）
        Db.CodeFirst.InitTables<CookBook>();
        Db.CodeFirst.InitTables<Ingredient>();
        Db.CodeFirst.InitTables<DailyPurchase>();
        Db.CodeFirst.InitTables<DailyPurchaseDetail>();
        Db.CodeFirst.InitTables<RecipeIngredient>();
        Db.CodeFirst.InitTables<WeeklyMenu>();

        // 启用软删除功能
        InitSoftDeleteForTables();
    }

    private void InitSoftDeleteForTables()
    {
        // 为每个表启用软删除，确保 IsDeleted 字段存在
        Db.Updateable<CookBook>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
        Db.Updateable<Ingredient>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
        Db.Updateable<DailyPurchase>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
        Db.Updateable<DailyPurchaseDetail>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
        Db.Updateable<RecipeIngredient>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
        Db.Updateable<WeeklyMenu>().SetColumns(it => it.IsDeleted == false).Where(it => false).ExecuteCommand();
    }

    public SimpleClient<CookBook> CookBooks => new SimpleClient<CookBook>(Db);
    public SimpleClient<Ingredient> Ingredients => new SimpleClient<Ingredient>(Db);
    public SimpleClient<DailyPurchase> DailyPurchases => new SimpleClient<DailyPurchase>(Db);
    public SimpleClient<DailyPurchaseDetail> DailyPurchaseDetails => new SimpleClient<DailyPurchaseDetail>(Db);
    public SimpleClient<RecipeIngredient> RecipeIngredients => new SimpleClient<RecipeIngredient>(Db);
    public SimpleClient<WeeklyMenu> WeeklyMenus => new SimpleClient<WeeklyMenu>(Db);
}